package com.htgd.gardenexpo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.htgd.gardenexpo.dto.WeChatQrCodeRequest;
import com.htgd.gardenexpo.vo.WeChatAccessTokenVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 王秀田
 * @date: 2024/11/20 13:43
 * @description: TODO
 */
@Component
@Slf4j
public class WeChatUtils {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${applet.version}")
    private String version;

    @Value("${wx.public.appId}")
    public String appId;

    @Value("${wx.public.appsecret}")
    public String appsecret;

    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static final String QR_CODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";

    private static final String QR_CODE_URL1 = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=";

    public String getAccessToken(String appId, String secret) {
        String url = TOKEN_URL + "?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        WeChatAccessTokenVO response = restTemplate.getForObject(url, WeChatAccessTokenVO.class);
        return response.getAccess_token();
    }

    public byte[] createQRCode(String accessToken, String page, String scene) {
        String url = QR_CODE_URL + accessToken;
        Map<String, Object> param = new HashMap<>();
        param.put("scene", scene);
        param.put("page", page);
        param.put("width", 430);
        param.put("auto_color", false);
//        param.put("env_version","trial");
        param.put("env_version",version);
        param.put("check_path",false);
//        WeChatQrCodeRequest request = new WeChatQrCodeRequest(page,scene,false,"develop",430,false,true);
//        ResponseEntity<byte[]> response = restTemplate.postForEntity(url, request, byte[].class);
        byte[] bytes = new byte[0];
        try {
            bytes = doPost(url, JSON.toJSONString(param));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bytes;
    }

    public static byte[] doPost(String url, String json) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
        CloseableHttpResponse response = client.execute(post);
        byte[] bytes = EntityUtils.toByteArray(response.getEntity());
        response.close();
        return bytes;
    }


    public static String convert(String longString) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(longString.getBytes());
            String shortString = new BigInteger(1, messageDigest.digest()).toString(18);
            return shortString;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String grant_type = "client_credential";//获取access_token填写client_credential
        String AppId= "wxd4927ab426d66831";//第三方用户唯一凭证
        String secret= "f6ed8456429fa4f3c70c869b677baaa1";//第三方用户唯一凭证密钥，即appsecret
        //这个url链接地址和参数皆不能变
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;

        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject demoJson = JSONObject.parseObject(message);
            System.out.println("JSON字符串："+demoJson);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //内容检查
    public JSONObject msgCheck(String content, String openId) {
        String accessToken = getAccessToken(appId,appsecret);
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        //封装请求体
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content", content);
        paramMap.put("version", 2);
        paramMap.put("scene", 2);
        paramMap.put("openid", openId);

        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap,headers);

        //通过RestTemplate发送请求，获取到用户手机号码
        String response = restTemplate.postForObject(url, request, String.class);
        JSONObject responseJSON = JSONObject.parseObject(response);
        return  responseJSON;
    }

    //图片检查
    public JSONObject mediaCheck(String mediaUrl, String openId) {
        String accessToken = getAccessToken(appId,appsecret);
        String url = "https://api.weixin.qq.com/wxa/media_check_async?access_token=" + accessToken;

        //封装请求体
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("media_url", mediaUrl);
        paramMap.put("media_type", 2);
        paramMap.put("version", 2);
        paramMap.put("scene", 3);
        paramMap.put("openid", openId);

        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(paramMap,headers);

        //通过RestTemplate发送请求，获取到用户手机号码
        String response = restTemplate.postForObject(url, request, String.class);
        JSONObject responseJSON = JSONObject.parseObject(response);
        return  responseJSON;
    }

    //获取日活跃数
    public JSONObject getDailyActivityCount(String beginDate,String endDate) {
        String accessToken = getAccessToken(appId,appsecret);
        String url = "https://api.weixin.qq.com/datacube/getweanalysisappiddailyretaininfo?access_token=" + accessToken;

        //封装请求体
        JSONObject param = new JSONObject();
        param.put("begin_date", beginDate);
        param.put("end_date", endDate);

        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<JSONObject> request = new HttpEntity<>(param,headers);

        //通过RestTemplate发送请求，获取到用户手机号码
        ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
        JSONObject responseJSON = JSON.parseObject(responseEntity.getBody().toString());
        return  responseJSON;
    }
}
